package com.squid.templateProject.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 实体类自动添加创建人，创建时间，修改人和修改时间
 *
 * @author jh
 * @date 2022/11/30 14:31
 */
@Component
@Slf4j
public class CustomizeMetaObjectHandler implements MetaObjectHandler {
    /**
     * 未登录用户默认用户名
     */
    private static final String DEFAULT_CONSTANT_USER = "0";

    private static final String CREATE_USER = "createUser";
    private static final String UPDATE_USER = "updateUser";
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";


    /**
     * 添加字段时自动填充策略
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        String createUser = DEFAULT_CONSTANT_USER;
        String updateUser = DEFAULT_CONSTANT_USER;
        //获取到当前线程绑定的请求对象
        String currUsername = "";
        if (StringUtils.hasText(currUsername)) {
            createUser = currUsername;
            updateUser = currUsername;
        }
        this.setFieldValByName(CREATE_TIME, date, metaObject);
        this.setFieldValByName(UPDATE_TIME, date, metaObject);
        this.setFieldValByName(CREATE_USER, createUser, metaObject);
        this.setFieldValByName(UPDATE_USER, updateUser, metaObject);
        log.info("插入数据获取到当前登录人为:{}，时间为:{}", createUser, date);
    }

    /**
     * 修改字段时自动填充策略
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        String updateUser = DEFAULT_CONSTANT_USER;
        //获取到当前线程绑定的请求对象
        String currUsername = "";
        if (StringUtils.hasText(currUsername)) {
            updateUser = currUsername;
        }
        this.setFieldValByName(UPDATE_TIME, date, metaObject);
        this.setFieldValByName(UPDATE_USER, updateUser, metaObject);
        log.info("更新数据获取到当前登录人为:{}，时间为:{}", updateUser, date);
    }
}
